import React from "react";

export interface FlowNode {
  nodeId: string;
  nodeLabel: string;
  status: string;
  event: string;
  data?: any;
  timestamp?: number;
}

interface FlowNodesProps {
  nodes: FlowNode[];
}

const FlowNodes: React.FC<FlowNodesProps> = ({ nodes }) => {
  const [expanded, setExpanded] = React.useState(true);
  const [expandedNodes, setExpandedNodes] = React.useState<
    Record<string, boolean>
  >({});

  const toggleNodeExpanded = (nodeId: string) => {
    setExpandedNodes((prev) => ({
      ...prev,
      [nodeId]: !prev[nodeId],
    }));
  };

  const formatNodeData = (node: FlowNode) => {
    if (!node.data) return null;

    // 特殊处理不同类型的节点数据
    if (node.event === "calledTools") {
      if (Array.isArray(node.data) && node.data.length === 0) {
        return (
          <span style={{ color: "#888", fontStyle: "italic" }}>无工具调用</span>
        );
      }
      return (
        <pre
          style={{
            background: "#f5f5f5",
            padding: 6,
            borderRadius: 4,
            marginTop: 4,
            fontSize: 12,
            color: "#333",
            maxWidth: 320,
            overflowX: "auto",
          }}
        >
          {JSON.stringify(node.data, null, 2)}
        </pre>
      );
    }

    if (node.event === "usageMetadata") {
      const usage = node.data;
      return (
        <div
          style={{
            background: "#f5f5f5",
            padding: 6,
            borderRadius: 4,
            marginTop: 4,
            fontSize: 12,
          }}
        >
          <div>
            <strong>Token 使用:</strong>
          </div>
          <div>输入: {usage.input_tokens || 0}</div>
          <div>输出: {usage.output_tokens || 0}</div>
          <div>总计: {usage.total_tokens || 0}</div>
          {usage.input_token_details && (
            <div>
              详情: 音频({usage.input_token_details.audio}), 缓存(
              {usage.input_token_details.cache_read})
            </div>
          )}
        </div>
      );
    }

    if (node.event === "metadata") {
      const metadata = node.data;
      return (
        <div
          style={{
            background: "#f5f5f5",
            padding: 6,
            borderRadius: 4,
            marginTop: 4,
            fontSize: 12,
          }}
        >
          <div>
            <strong>会话信息:</strong>
          </div>
          <div>Chat ID: {metadata.chatId}</div>
          <div>Message ID: {metadata.chatMessageId}</div>
          <div>Session ID: {metadata.sessionId}</div>
          <div>问题: {metadata.question}</div>
        </div>
      );
    }

    // 默认 JSON 显示
    return (
      <pre
        style={{
          background: "#f5f5f5",
          padding: 6,
          borderRadius: 4,
          marginTop: 4,
          fontSize: 12,
          color: "#333",
          maxWidth: 320,
          overflowX: "auto",
        }}
      >
        {JSON.stringify(node.data, null, 2)}
      </pre>
    );
  };

  return (
    <div
      style={{
        background: "#fafafa",
        padding: 8,
        borderRadius: 4,
        marginBottom: 8,
      }}
    >
      <div
        style={{ display: "flex", alignItems: "center", cursor: "pointer" }}
        onClick={() => setExpanded((e) => !e)}
      >
        <b>流程节点 ({nodes.length})</b>
        <span style={{ marginLeft: 8, color: "#888", fontSize: 12 }}>
          {expanded ? "收起 ▲" : "展开 ▼"}
        </span>
      </div>
      {expanded &&
        (nodes.length === 0 ? (
          <span style={{ color: "#aaa" }}>暂无</span>
        ) : (
          <div style={{ marginTop: 8 }}>
            {nodes.map((node, idx) => {
              const nodeKey = `${node.nodeId}_${idx}`;
              const isNodeExpanded = expandedNodes[nodeKey];

              return (
                <div
                  key={nodeKey}
                  style={{
                    marginBottom: 8,
                    border: "1px solid #e0e0e0",
                    borderRadius: 4,
                    padding: 8,
                  }}
                >
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                    }}
                  >
                    <div>
                      <span style={{ fontWeight: 500 }}>{node.nodeLabel}</span>
                      <span style={{ marginLeft: 8, color: "#888" }}>
                        ({node.status})
                      </span>
                      <span
                        style={{ marginLeft: 8, color: "#666", fontSize: 11 }}
                      >
                        {node.event}
                      </span>
                    </div>
                    {node.data && (
                      <button
                        onClick={() => toggleNodeExpanded(nodeKey)}
                        style={{
                          background: "none",
                          border: "1px solid #ccc",
                          borderRadius: 4,
                          padding: "2px 6px",
                          cursor: "pointer",
                          fontSize: 11,
                        }}
                      >
                        {isNodeExpanded ? "收起" : "详情"}
                      </button>
                    )}
                  </div>
                  {isNodeExpanded && node.data && formatNodeData(node)}
                </div>
              );
            })}
          </div>
        ))}
    </div>
  );
};

export default FlowNodes;
